package com.wulwu.permission.service;

import com.wulwu.permission.entity.PermissionMenuInfo;
import com.wulwu.permission.mapper.PermissionMenuInfoMapper;
import com.wulwu.permission.mapper.UserInfoMapper;
import com.wulwu.permission.model.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description 自定义登录逻辑
 * @Author Major
 * @Date 2020/11/25 11:22
 */
@Service
public class SecurityUserDetailService implements UserDetailsService {

    @Autowired
    private PermissionMenuInfoMapper permissionMenuInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.获取用户
        UserEntity userEntity = userInfoMapper.queryUserAndPwdByUsername(username);
        if (Objects.isNull(userEntity)){
            throw new UsernameNotFoundException("用户不存在");
        }
        //2.获取权限
        List<PermissionMenuInfo> permissionList = permissionMenuInfoMapper.queryPermissionByUsername(username);
        //3.授权
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permissionList.forEach(e->{
            grantedAuthorities.add(new SimpleGrantedAuthority(e.getPermission()));
        });
        userEntity.setAuthorities(grantedAuthorities);
        userEntity.setAccountNonExpired(true);
        userEntity.setAccountNonLocked(true);
        userEntity.setEnabled(true);
        userEntity.setCredentialsNonExpired(true);
        return userEntity;
    }
}
